{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Accuracy Score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A function for computing for computing basic classifcation accuracy, per-class accuracy, and average per-class accuracy."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> from mlxtend.evaluate import accuracy_score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example 1 -- Standard Accuracy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The \"overall\" accuracy is defined as the number of correct predictions (*true positives* TP and *true negatives* TN) over all samples *n*:\n",
    "\n",
    "$$ACC = \\frac{TP + TN}{n}$$\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.5555555555555556"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "from mlxtend.evaluate import accuracy_score\n",
    "\n",
    "\n",
    "y_targ = [0, 0, 0, 1, 1, 1, 2, 2, 2]\n",
    "y_pred = [1, 0, 0, 0, 1, 2, 0, 2, 2]\n",
    "\n",
    "accuracy_score(y_targ, y_pred)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example 2 -- Per-Class Accuracy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The per-class accuracy is the accuracy of one class (defined as the `pos_label`) versus all remaining datapoints in the dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Standard accuracy: 55.56%\n",
      "Class 1 accuracy: 66.67%\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "from mlxtend.evaluate import accuracy_score\n",
    "\n",
    "\n",
    "y_targ = [0, 0, 0, 1, 1, 1, 2, 2, 2]\n",
    "y_pred = [1, 0, 0, 0, 1, 2, 0, 2, 2]\n",
    "\n",
    "std_acc = accuracy_score(y_targ, y_pred)\n",
    "bin_acc = accuracy_score(y_targ, y_pred, method='binary', pos_label=1)\n",
    "\n",
    "print(f'Standard accuracy: {std_acc*100:.2f}%')\n",
    "print(f'Class 1 accuracy: {bin_acc*100:.2f}%')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example 3 -- Average Per-Class Accuracy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Overview"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The \"overall\" accuracy is defined as the number of correct predictions (*true positives* TP and *true negatives* TN) over all samples *n*:\n",
    "\n",
    "$$ACC = \\frac{TP + TN}{n}$$\n",
    "\n",
    "in a binary class setting:\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](./scoring_files/conf_mat_binary-1.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In a multi-class setting, we can generalize the computation of the accuracy as the fraction of all true predictions (the diagonal) over all samples n.\n",
    "\n",
    "$$ACC = \\frac{T}{n}$$\n",
    "\n",
    "Considering a multi-class problem with 3 classes (C0, C1, C2)\n",
    "\n",
    "![](./scoring_files/conf_mat_multi-1.png)\n",
    "\n",
    "let's assume our model made the following predictions:\n",
    "\n",
    "![](./scoring_files/multi-ex-1.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We compute the accuracy as:\n",
    "    \n",
    "$$ACC = \\frac{3 + 50 + 18}{90} \\approx 0.79$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, in order to compute the ***average per-class accuracy***, we compute the binary accuracy for each class label separately; i.e., if class 1 is the positive class, class 0 and 2 are both considered the negative class.\n",
    "\n",
    "$$APC\\;ACC = \\frac{83/90 + 71/90 + 78/90}{3} \\approx 0.86$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Standard accuracy: 55.56%\n",
      "Class 1 accuracy: 66.67%\n",
      "Average per-class accuracy: 70.37%\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "from mlxtend.evaluate import accuracy_score\n",
    "\n",
    "\n",
    "y_targ = [0, 0, 0, 1, 1, 1, 2, 2, 2]\n",
    "y_pred = [1, 0, 0, 0, 1, 2, 0, 2, 2]\n",
    "\n",
    "std_acc = accuracy_score(y_targ, y_pred)\n",
    "bin_acc = accuracy_score(y_targ, y_pred, method='binary', pos_label=1)\n",
    "avg_acc = accuracy_score(y_targ, y_pred, method='average')\n",
    "\n",
    "print(f'Standard accuracy: {std_acc*100:.2f}%')\n",
    "print(f'Class 1 accuracy: {bin_acc*100:.2f}%')\n",
    "print(f'Average per-class accuracy: {avg_acc*100:.2f}%')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### References\n",
    "\n",
    "- [1] S. Raschka. [An overview of general performance metrics of binary classifier systems](http://arxiv.org/abs/1410.5330). Computing Research Repository (CoRR), abs/1410.5330, 2014.\n",
    "- [2] Cyril Goutte and Eric Gaussier. [A probabilistic interpretation of precision, recall and f-score, with implication for evaluation](http://link.springer.com/chapter/10.1007/978-3-540-31865-1_25). In Advances in Information Retrieval, pages 345–359. Springer, 2005.\n",
    "- [3] Brian W Matthews. [Comparison of the predicted and observed secondary structure of T4 phage lysozyme](http://www.sciencedirect.com/science/article/pii/0005279575901099). Biochimica et Biophysica Acta (BBA)- Protein Structure, 405(2):442–451, 1975."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## API"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "## accuracy_score\n",
      "\n",
      "*accuracy_score(y_target, y_predicted, method='standard', pos_label=1, normalize=True)*\n",
      "\n",
      "General accuracy function for supervised learning.\n",
      "**Parameters**\n",
      "\n",
      "- `y_target` : array-like, shape=[n_values]\n",
      "\n",
      "    True class labels or target values.\n",
      "\n",
      "- `y_predicted` : array-like, shape=[n_values]\n",
      "\n",
      "    Predicted class labels or target values.\n",
      "\n",
      "- `method` : str, 'standard' by default.\n",
      "\n",
      "    The chosen method for accuracy computation.\n",
      "    If set to 'standard', computes overall accuracy.\n",
      "    If set to 'binary', computes accuracy for class pos_label.\n",
      "    If set to 'average', computes average per class accuracy.\n",
      "\n",
      "- `pos_label` : str or int, 1 by default.\n",
      "\n",
      "    The class whose accuracy score is to be reported.\n",
      "    Used only when `method` is set to 'binary'\n",
      "\n",
      "- `normalize` : bool, True by default.\n",
      "\n",
      "    If True, returns fraction of correctly classified samples.\n",
      "    If False, returns number of correctly classified samples.\n",
      "\n",
      "**Returns**\n",
      "\n",
      "score: float\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "with open('../../api_modules/mlxtend.evaluate/accuracy_score.md', 'r') as f:\n",
    "    print(f.read())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  },
  "toc": {
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
